import { defineStore } from 'pinia'
import { UserState } from './types'
import { refreshUserInfo, userLogin } from '@/api/user'

//命名规则：  use模块名Store
export const useUserStore = defineStore('User', {
    // 共享数据
    state: () => ({
        username: 'jack',
        accessToken: '',
        roles: ['common']
    }),
    // 快捷访问
    getters: {},
    // 修改操作
    actions: {
        // 更新store数据
        updateInfo(partial: Partial<UserState>) {
            this.$patch(partial)
        },
        // 用户登录
        async storeUserLogin(data) {
            const res = await userLogin(data)
            this.username = res.username
            this.roles = res.roles
            this.accessToken = res.accessToken
            return res
        },
        // 刷新用户信息
        async refreshUserInfo() {
            try {
                if (this.username !== 'jack' && this.accessToken === '') return
                const res = await refreshUserInfo({ accessToken: this.accessToken })
                this.username = res.username
                this.roles = res.roles
                this.accessToken = res.accessToken
            } catch (error) {
                this.accessToken = ''
            }
        }
    },
    // 持久化保存 accessToken
    persist: {
        key: 'userInfo',
        storage: sessionStorage,
        paths: ['accessToken']
    }
})
